/**
 *
 */
package com.lt.report.controller.common;

import com.alibaba.fastjson.JSON;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JqGrid抽象父类，指定方法返回值与参数
 *
 * @author Daniel
 */
public abstract class TableBaseController<T> {

    private static final Logger logger = LoggerFactory.getLogger(TableBaseController.class);

    /**
     * 相应页面请求
     *
     * @author Daniel
     * @time 2017年6月21日
     */
    public abstract TableResponseVO<T> list(TableRequestVO tableRequestVO, HttpServletRequest request);

    /**
     * 返回查询结果
     *
     * @author Daniel
     * @time 2017年6月21日
     */
    public abstract List<T> listResults(Map<String, Object> params, HttpServletRequest request);

    public abstract Long getListCount(Map<String, Object> params);


    /**
     * 查询并封装jqgrid返回结果
     *
     * @param tableRequestVO JqGrid请求参数封装类
     * @author Daniel
     * @time 2017年6月27日
     */
    public TableResponseVO<T> refreshGridModelByCondi(final TableRequestVO tableRequestVO,
                                                      final HttpServletRequest request) {
        try {
            final TableResponseVO<T> tableResponseVO = new TableResponseVO<T>();
            List<T> results = Collections.emptyList();

            final Map<String, Object> searchMap = new HashMap<>();
            String sort = tableRequestVO.getSort();
            String dbSort = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,sort);
            searchMap.put("sort", dbSort);
            searchMap.put("order", tableRequestVO.getOrder());
            searchMap.put("limit", tableRequestVO.getLimit());
            searchMap.put("offset", tableRequestVO.getOffset());
            String searchField = tableRequestVO.getSearchField();
            if (StringUtils.isNotBlank(searchField)) {
                final Map<String, Object> searchFieldMap = JSON.parseObject(searchField, HashMap.class);
                searchMap.putAll(searchFieldMap);
            }


            results = this.listResults(searchMap, request);// 获取记录结果
            Long total = getListCount(searchMap);
            tableResponseVO.setRows(results);
            tableResponseVO.setTotal(total);
            return tableResponseVO;
        } catch (final Throwable e) {
            logger.error("Table加载错误", e);
            return null;
        }
    }
}
